package com.mathmodeling.controller;

import com.mathmodeling.dto.ApiResponse;
import com.mathmodeling.entity.Result;
import com.mathmodeling.entity.Work;
import com.mathmodeling.entity.Team;
import com.mathmodeling.entity.Topic;
import com.mathmodeling.repository.ResultRepository;
import com.mathmodeling.repository.WorkRepository;
import com.mathmodeling.repository.TeamRepository;
import com.mathmodeling.repository.TopicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/contests")
public class ContestController {
    
    @Autowired
    private ResultRepository resultRepository;
    
    @Autowired
    private WorkRepository workRepository;
    
    @Autowired
    private TeamRepository teamRepository;
    
    @Autowired
    private TopicRepository topicRepository;
    
    /**
     * 获取竞赛成绩排名 - 严格按照API文档规范
     */
    @GetMapping("/results")
    public ApiResponse<List<ContestResultResponse>> getContestResults(@RequestParam String contestId) {
        try {
            // 验证参数
            if (contestId == null || contestId.trim().isEmpty()) {
                return ApiResponse.error(400, "竞赛ID不能为空");
            }
            
            // 获取该竞赛的所有作品
            List<Work> works = workRepository.findByContestId(contestId);
            if (works.isEmpty()) {
                return ApiResponse.error(404, "未找到该竞赛的作品");
            }
            
            // 获取所有结果并按排名排序
            List<Result> results = resultRepository.findAllByOrderByRankAsc();
            
            // 转换为API文档要求的响应格式
            List<ContestResultResponse> responses = results.stream()
                    .filter(result -> {
                        // 过滤出属于该竞赛的结果
                        Work work = workRepository.findById(result.getWorkId()).orElse(null);
                        return work != null && contestId.equals(work.getContestId());
                    })
                    .map(result -> {
                        ContestResultResponse response = new ContestResultResponse();
                        response.setRank(result.getRank());
                        
                        // 获取作品信息
                        Work work = workRepository.findById(result.getWorkId()).orElse(null);
                        if (work != null) {
                            response.setTeamId(work.getTeamId());
                            
                            // 获取团队信息
                            Team team = teamRepository.findById(work.getTeamId()).orElse(null);
                            if (team != null) {
                                response.setTeamName(team.getName());
                            }
                            
                            // 获取题目信息
                            Topic topic = topicRepository.findById(work.getTopicId()).orElse(null);
                            if (topic != null) {
                                response.setTopic(topic.getName());
                            }
                        }
                        
                        // 计算平均分（去掉最高分和最低分后的平均分）
                        response.setAverageScore(calculateAverageScore(result.getFinalScore()));
                        response.setFullScore(100); // 满分值
                        
                        return response;
                    })
                    .collect(Collectors.toList());
            
            return ApiResponse.success("成绩已公布", responses);
            
        } catch (Exception e) {
            return ApiResponse.error(500, "获取竞赛结果失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算平均分（简化实现，实际应该根据多个评分计算）
     */
    private Float calculateAverageScore(Float finalScore) {
        // 这里简化实现，实际应该根据多个评分去掉最高分和最低分后计算平均分
        return finalScore;
    }
    
    // 响应类
    public static class ContestResultResponse {
        private Integer rank;
        private String teamId;
        private String teamName;
        private String topic;
        private Float averageScore;
        private Integer fullScore;
        
        // Getters and Setters
        public Integer getRank() { return rank; }
        public void setRank(Integer rank) { this.rank = rank; }
        
        public String getTeamId() { return teamId; }
        public void setTeamId(String teamId) { this.teamId = teamId; }
        
        public String getTeamName() { return teamName; }
        public void setTeamName(String teamName) { this.teamName = teamName; }
        
        public String getTopic() { return topic; }
        public void setTopic(String topic) { this.topic = topic; }
        
        public Float getAverageScore() { return averageScore; }
        public void setAverageScore(Float averageScore) { this.averageScore = averageScore; }
        
        public Integer getFullScore() { return fullScore; }
        public void setFullScore(Integer fullScore) { this.fullScore = fullScore; }
    }
} 